<?php
/**
 * Created by PhpStorm.
 * User: kaycn
 * Date: 18-9-13
 * Time: 下午1:08
 */
namespace Pay;

class img{

   protected function GetSign($usr_id, $usr_key, $timestamp){
        $chk_sign1 	= md5( $timestamp . $usr_key);
        $chk_sign2	= md5( $usr_id . $timestamp . $chk_sign1);
        return $chk_sign2;
    }

    protected function Post($url,$post_data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);	//设置本机的post请求超时时间
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    protected function ArrayToPostData($data){

        $post_data 		= "";
        $first_flag 	= true;
        foreach( $data as $key => $val){
            if( $first_flag == true){
                $first_flag = false;
            }else{
                $post_data = $post_data . "&";
            }
            $post_data = $post_data . $key . "=" . $val;
        }
        return $post_data;
    }

    public function __construct( $app_id, $app_key, $usr_id, $usr_key){
        $this->app_id   = $app_id;
        $this->app_key  = $app_key;
        $this->usr_id   = $usr_id;
        $this->usr_key  = $usr_key;
        $this->host     = "http://pred.fateadm.com";
    }

    public function Predict($predict_type, $img_data){
        $timestamp 		= time();
        $sign 			= $this->GetSign( $this->usr_id, $this->usr_key, $timestamp);
        $data 			= array(
            'user_id' => $this->usr_id,
            'timestamp' => $timestamp,
            'sign' => $sign,
            'predict_type' => $predict_type,
            'img_data' => $img_data,
        );
        if( $this->app_id != ""){
            $asing      = $this -> GetSign( $this->app_id, $this->app_key,  $timestamp);
            $data["appid"]  = $this->app_id;

        }
        $url 			= $this->host . "/api/capreg";
        $post_data		= $this -> ArrayToPostData($data);
        $rsp 			= $this->Post($url, $post_data);
        $json_rsp 		= json_decode( $rsp,true);

        return $json_rsp;
    }

    public function deel($file_name="/tmp/a.png",$predict_type=30400){

        $img_data 		= urlencode(base64_encode( file_get_contents($file_name)));
        $rsp            = $this->Predict($predict_type, $img_data);

        return $rsp;
    }


}

